package cn.edu.scujcc.customofsichuan;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import cn.edu.scujcc.customofsichuan.Application.UserApplication;
import cn.edu.scujcc.customofsichuan.Dao.UserDao;
import cn.edu.scujcc.customofsichuan.DataBase.UserDatabase;
import cn.edu.scujcc.customofsichuan.Entity.User;

public class login extends AppCompatActivity {

    private Button bt_log;
    private TextView iv_register;
    private CheckBox bt_remember_password;
    private String text_account;
    private String text_password;
    private EditText et_account;
    private EditText et_password;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //创建SharedPreferences
        sharedPreferences = getSharedPreferences("local_user", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        //创建数据库
        UserDatabase userDatabase = UserDatabase.getInstance(this);
        UserDao userDao = userDatabase.getUserDao();

        et_account = findViewById(R.id.login_account);
        et_password = findViewById(R.id.login_password);

        bt_log = findViewById(R.id.login_log);
        iv_register = findViewById(R.id.login_register);
        bt_remember_password = findViewById(R.id.login_remember_password);

        //自动加载本地保存的用户数据
        loadData();

        iv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                intent=new Intent(v.getContext(),Rigister.class);
                startActivity(intent);
            }
        });

        bt_log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //异步查询
               new selectUserTask(userDao).execute();

            }
        });

    }

    private void loadData() {
        String account = sharedPreferences.getString("account", null);
        String password = sharedPreferences.getString("password", null);
        boolean status = sharedPreferences.getBoolean("status", false);
        if (account!=null&&password!=null){
            et_account.setText(account);
            et_password.setText(password);
            bt_remember_password.setChecked(status);
        }
    }

    //异步查询
    class selectUserTask extends AsyncTask<Void, Void, Void> {
        private UserDao userDao;

        public selectUserTask(UserDao userDao) {
            this.userDao = userDao;
        }
        @Override
        protected Void doInBackground(Void... voids) {
            //获取数据
            text_account = et_account.getText().toString().trim();
            text_password = et_password.getText().toString().trim();

            if (text_account.equals("")==true||text_password.equals("")==true){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(login.this, "账号或密码不能为空！", Toast.LENGTH_SHORT).show();
                    }
                });
            }else {
                //当输入的内容不为空的时候才开始查询数据库
                User db_user = userDao.selectByAccount(text_account);
                selectDataBase(db_user);
            }
            return null;
        }
    }



    //查询数据库
    private void selectDataBase(User db_user) {

        //如果数据库中查不到该账号，如果不判断，会在调用db_user.getAccount()时出现空指针错误！！因此必须加以判断
        if (db_user==null){
            //再子线程中无法将数据显示到主线程中，因此调用以下方法将提示语句显示在主线程中
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(login.this, "该账户不存在！", Toast.LENGTH_SHORT).show();
                }
            });

        }else {
            //账户与密码均正确才能跳转
            if (db_user.getAccount().equals(text_account)&&db_user.getPassword().equals(text_password)){

                //成功登录后跳转到主界面
                Intent intent=new Intent(login.this,MainActivity.class);
                startActivity(intent);


                //确保用户名和密码正确才将数据保存到本地，并且通过异步方式执行，不会导致主界面卡顿
                if (bt_remember_password.isChecked()==true){
                    text_account = et_account.getText().toString().trim();
                    text_password = et_password.getText().toString().trim();
                    //通过SharedPreference存储到本地
                    editor.putString("account",text_account);
                    editor.putString("password",text_password);
                    editor.putBoolean("status",true);
                    editor.commit();
                }else {
                    editor.putString("account",null);
                    editor.putString("password",null);
                    editor.putBoolean("status",false);
                    editor.commit();
                }



                //将该用户数据保存到全局变量Application中
                UserApplication userInfo = UserApplication.getInstance();
                if (db_user.getHead_image()==null){
                    userInfo.userMap.put("userHead",R.drawable.live_head);
                }else {
                    userInfo.userMap.put("userHead",db_user.getHead_image());
                }
                userInfo.userMap.put("userName",db_user.getUserName());
                userInfo.userMap.put("userAccount",db_user.getAccount());
                userInfo.userMap.put("userPassword",db_user.getPassword());
                if (db_user.getTalk()==null){
                    userInfo.userMap.put("userTalk","说点什么吧...");
                }else {
                    userInfo.userMap.put("userTalk",db_user.getTalk());
                }


            }else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(login.this, "密码错误！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }



}